import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:interview/components/interview/interview_item.dart';
import 'package:interview/components/page/page_empty.dart';
import 'package:interview/components/page/page_list_custom.dart';
import 'package:interview/components/page/page_load.dart';
import 'package:interview/controller/interview_controller.dart';
import 'package:interview/providers/app_refresh_providers.dart';
import 'package:interview/theme/app_colors.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class InterviewList extends StatefulWidget {
  final String tab;
  const InterviewList({super.key, required this.tab});

  @override
  State<InterviewList> createState() => _InterviewListState();
}

class _InterviewListState extends State<InterviewList> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true; // 保持页面状态
  final RefreshController _refreshController = RefreshController(initialRefresh: false);
  final InterviewController interviewController = Get.find<InterviewController>();
  late InterviewState interviewState;

  Future <void> _onRefresh () async{
    _refreshController.resetNoData(); // 这里重置状态
    await interviewController.refreshInterviews(context: context, tab:widget.tab ,  keyword: widget.tab);
    _refreshController.refreshCompleted();
  }

  Future <void> _onLoading () async{
    await interviewController.loadMoreInterViews(context: context, tab: widget.tab ,  keyword: widget.tab);
    if(interviewState.isFinished.value){
      _refreshController.loadNoData();
    }else{
      _refreshController.loadComplete();
    }
  }

  @override
  void initState() {
    super.initState();
    interviewState = interviewController.getInterviewState(widget.tab);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _onLoading();
    });
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context).extension<AppColors>()!;
    super.build(context);
    return Consumer<AppRefreshProvider>(
      builder: (context,refreshNotifier , child){
        if(refreshNotifier.shouldRefresh && mounted){
          WidgetsBinding.instance.addPostFrameCallback((_){
            _onLoading().then((_){
              refreshNotifier.resetRefresh();
            });
          });
        }
        return Obx((){
          final interviewList = interviewState.interviewList;
          return SmartRefresher(
            controller: _refreshController,
            enablePullDown: true,
            enablePullUp: true,
            header: const ListCustomHeader(),
            footer:const ListCustomFooter(),
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            child: interviewList.isEmpty?(interviewState.isFinished.value ? const PageEmpty(): const PageLoad(width: 2)):
            ListView.separated(
              itemCount: interviewList.length,
              itemBuilder: (context,index) {
                final item = interviewList[index];
                return InterviewItem(
                  tab:widget.tab,
                  id:item.id,
                  ids:interviewList.map((i) => i.id).toList(),
                  theme: theme,
                  difficulty: item.difficulty,
                  content: item.content!,
                  subjectName: item.subjectName!,
                  creatorName: item.creatorName!,
                  createdAt: item.createdAt!,
                  creatorAvatar: item.creatorAvatar!,
                  stem:item.stem,
                  likeCount: item.likeCount.value,
                  likeFlag: 1,
                  questionType: item.questionType!,
                  views: item.views.value,
                );
              },
              separatorBuilder: (context, index) {
                return const Divider(
                  color: Color.fromARGB(255, 231, 231, 231), // 分割线颜色
                  height: 0.5, // 分割线高度
                  thickness: 0.5, // 分割线粗细
                  indent: 16, // 左侧缩进
                  endIndent: 16, // 右侧缩进
                );
              },
            ),
          );
        });
      }
    );
  }
}